<template>
  <Container>
    <template v-slot:searchForm>
      <div class="searchRow">
        <el-form class="elForm" ref="form" :model="searchFormData" label-width="80px">
          <el-form-item label="设备编码">
            <el-input v-model="searchFormData.deviceCode" clearable placeholder="请输入"></el-input>
          </el-form-item>
          <!-- <el-form-item label="数据类型">
            <el-input v-model="searchFormData.dataType" clearable placeholder="请输入"></el-input>
          </el-form-item> -->
        </el-form>
        <div class="btnList">
          <el-button type="danger" icon="el-icon-delete" @click="handleClickDel(selectionList)"
            :disabled="selectionList.length == 0" plain>删
            除</el-button>
          <el-button type="primary" icon="el-icon-circle-plus-outline" @click="handleClickAddEdit('add')" plain>添
            加</el-button>
          <el-button type="primary" icon="el-icon-search" @click="queryTableList" plain>查 询</el-button>
        </div>
      </div>
    </template>
    <template v-slot:table>
      <el-table :data="tableData" border height="100%" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55">
        </el-table-column>
        <el-table-column prop="deviceCode" label="设备编码" width="200">
        </el-table-column>
        <el-table-column prop="deviceTypeName" label="设备类型名称" width="200">
        </el-table-column>
        <el-table-column prop="address" label="设备地址">
        </el-table-column>
        <el-table-column prop="remark" label="设备描述">
        </el-table-column>
        <el-table-column prop="installDate" label="设备安装日期">
        </el-table-column>
        <el-table-column label="查看固件">
          <template slot-scope="scope">
            <el-button type="text" @click="lookViewFiles(scope.row)">点击查看</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="350">
          <template slot-scope="scope">
            <el-button type="text" @click="handleClickAddItem(scope.row, 'add')">分配数据项</el-button>
            <el-button type="text" @click="handleClickAddItem(scope.row, 'lookView')">查看数据项</el-button>
            <el-button type="text" @click="clearParam(scope.row.deviceCode)">清除数据项</el-button>
            <el-button type="text" @click="handleClickAddEdit('edit', scope.row)">编辑</el-button>
            <el-button type="text" @click="handleClickDel([scope.row])">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <AddEdit :title="'设备'" @closeDialog="closeDialog" :addEditFlag="addEditFlag" :dialogVisible="dialogVisible"
        :data="formData" :deviceTypeList="deviceTypeList">
      </AddEdit>
      <el-dialog title="固件列表" :visible.sync="dialogVisible_fileList" width="50%" :before-close="handleClose">
        <el-table :data="filesList" style="width: 100%" border>
          <el-table-column prop="fileName" label="文件名称">
          </el-table-column>
          <el-table-column prop="fileType" label="文件格式" width="200">
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template slot-scope="scope">
              <el-button type="text" @click="downloadFile(scope.row.filesId, scope.row.fileName,row)">文件下载</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>
      <el-dialog title="数据项" :visible.sync="dialogVisible_addItem" :width="dataItemFlag == 'add' ? '50%' : '90%'"
        :before-close="handleClose">
        <el-form style="width: 100%;" :model="ruleForm" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <!-- {{ JSON.stringify(dataItemListAll) }} -->
          <el-form-item label="选数据项" v-show="dataItemFlag == 'add'">
            <el-select class="w100p" v-model="ruleForm.dataItemIdList" clearable filterable multiple collapse-tags
              placeholder="选择选数据项">
              <el-option v-for="item, index in dataItemListAll" :key="index" :label="item.funcName"
                :value="item.dataItemId"></el-option>
            </el-select>
            <el-button type="text" @click="selectAll">全选</el-button>
            <el-button type="text" @click="clearSelectAll">清除</el-button>
          </el-form-item>
          <el-form-item label="已经选数据项" v-show="dataItemFlag == 'add'">
            <!-- {{ JSON.stringify(dataItemListAll) }} -->
            <el-tag size="small" v-if="ruleForm.dataItemIdList && ruleForm.dataItemIdList.length > 0"
              class="el-icon-close" @click="closeItem(item.dataItemId)"
              v-show="ruleForm.dataItemIdList.includes(item.dataItemId)" style="margin-right: 5px; cursor: pointer;"
              v-for="item, index in dataItemListAll" :key="index">{{ item.funcName
              }}</el-tag>
            <span v-show="!ruleForm.dataItemIdList || !ruleForm.dataItemIdList.length">请选择数据项</span>
          </el-form-item>
          <div class="choosedataItemIdList" v-if="dataItemFlag == 'lookView'">
            <div class="dataItem" v-for="deviceDataItem, index in ruleForm.choosedataItemIdList" :key="index">
              <div class="deviceDataItem">{{ '数据项' + (index + 1) }}</div>
              <el-form-item label="功能名称" :prop="`choosedataItemIdList[${index}].funcName`"
                :rules="{ required: true, message: '请输入', trigger: 'blur' }">
                <el-input class="w100p" v-model="deviceDataItem.funcName" placeholder="请输入功能名称"></el-input>
              </el-form-item>
              <el-form-item label="设备类型">
                <!-- <el-input class="w100p" v-model="ruleForm.dataType" placeholder="请输入设备类型"></el-input> -->
                <el-select v-model="deviceDataItem.deviceTypeId" class="w100p" clearable filterable
                  placeholder="请选择设备类型">
                  <el-option v-for="item, index in deviceTypeList" :label="item.deviceTypeName"
                    :value="item.deviceTypeId" :key="index"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="参数类型" prop="paramType">
                <el-input class="w100p" v-model="deviceDataItem.paramType" placeholder="请输入参数类型"></el-input>
              </el-form-item>
              <el-form-item label="权限等级" prop="privilegeLevel">
                <el-input type="number" class="w100p" v-model="deviceDataItem.privilegeLevel"
                  placeholder="请输入权限等级"></el-input>
              </el-form-item>
              <el-form-item label="读写" prop="readFlag">
                <el-input class="w100p" v-model="deviceDataItem.readFlag" placeholder="请输入"></el-input>
              </el-form-item>
              <el-form-item label="区间" prop="section">
                <el-input class="w100p" v-model="deviceDataItem.section" placeholder="请输入"></el-input>
              </el-form-item>
              <el-form-item label="单位" prop="unit">
                <el-input class="w100p" v-model="deviceDataItem.unit" placeholder="请输入"></el-input>
              </el-form-item>
              <el-form-item label="定义" prop="definition">
                <el-input class="w100p" v-model="deviceDataItem.definition" placeholder="请输入"></el-input>
              </el-form-item>
              <el-form-item label="操作">
                <i class="el-icon-circle-plus-outline" style="font-size: 20px;"
                  v-show="ruleForm.choosedataItemIdList.length == index + 1" @click="addDataItem()"></i>
                <i class="el-icon-remove-outline" style="font-size: 20px;"
                  v-show="ruleForm.choosedataItemIdList.length > 1" @click="delDataItem(index)"></i>
              </el-form-item>
            </div>
          </div>

        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible_addItem = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </el-dialog>
    </template>
    <template v-slot:pagination>
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="page" :page-sizes="[10, 100, 200, 300, 400, 500, 600]" :page-size="size"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </template>
  </Container>
</template>

<script>
import Container from "@/components/Container"
import AddEdit from './components/addEdit';
import device from "@/api/device";
import dataItem from "@/api/dataItem";
import deviceType from "@/api/deviceType"
import files from "@/api/files";
export default {
  components: { Container, AddEdit },
  data() {
    return {
      searchFormData: {},
      tableData: [],
      selectionList: [],
      deviceTypeList: [],
      page: 1,
      size: 100,
      total: 10,
      addEditFlag: 'add',
      dataItemFlag: 'add',
      dialogVisible: false,
      dialogVisible_addItem: false,
      dialogVisible_fileList: false,
      formData: {},
      ruleForm: {
        dataItemIdList: []
      },
      dataItemList: [],
      dataItemListAll: [],
      choosedataItemIdList: [],
      filesList: []
    }
  },
  watch: {},
  mounted() {
    this.queryTableList();
    this.queryDeviceTypeList();
  },
  methods: {
    async queryDeviceTypeList() {
      let { data: dataItemList } = await dataItem.queryList();
      let { data: deviceTypeList } = await deviceType.queryList();
      this.dataItemListAll = dataItemList || []
      console.log(this.dataItemListAll)
      if (!deviceTypeList || deviceTypeList.length == 0) {
        this.$message.warning('请先创建设备类型')
      } else {
        this.deviceTypeList = deviceTypeList || [];
      }
    },
    async queryByDeviceTypeId(id) {
      let { data } = await dataItem.queryByDeviceTypeId(id);
      console.log(data)
    },
    async downloadFile(fileId, fileName,row) {
      if (row.iisAddress) {
        window.open(row.iisAddress, '_blank');
        return
      }
      try {
        // 发起GET请求来获取文件  
        this.$notify.info({
          title: '消息',
          message: `${fileName}文件下载中,请稍后! `,
          position: 'bottom-right'
        });
        const response = await files.download(fileId);
        this.downLoadFileBlob(response, fileName);
      } catch (error) {
        console.error('下载文件时出错：', error);
      }
    },
    //如果后端返回的是流
    downLoadFileBlob(FileBlob, fileName) {
      const blob = new Blob([FileBlob]);
      console.log(blob)
      // 创建一个隐藏的a标签来下载文件  
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.setAttribute('download', fileName); // 设置下载文件的名称  
      document.body.appendChild(link);
      link.click(); // 触发下载操作  
      // 清理：移除隐藏的a标签，并释放URL对象  
      document.body.removeChild(link);
      URL.revokeObjectURL(link.href);
      this.$notify.success({
        title: '成功',
        message: `${fileName}文件下载成功! `,
        position: 'bottom-right'
      });
    },
    addDataItem() {
      let index = this.ruleForm.choosedataItemIdList.length
      this.$set(this.ruleForm.choosedataItemIdList, index, {
        "dataAddress": "",
        "dataType": "",
        "definition": "",
        "deviceTypeId": '',
        "funcName": "",
        "paramType": "",
        "privilegeLevel": 0,
        "readFlag": "",
        "section": "",
        "unit": ""
      })
    },
    async lookViewFiles(row) {
      let deviceCode = row.deviceCode;
      this.filesList = []
      let { data } = await device.getFilesByDeviceCode(deviceCode);
      this.filesList = data || [];
      if (this.filesList.length > 0) {
        this.dialogVisible_fileList = true;
      } else {
        this.$message.info('未关联固件')
      }
    },
    delDataItem(index) {
      let list = JSON.parse(JSON.stringify(this.ruleForm.choosedataItemIdList));
      list.splice(index, 1);
      this.$set(this.ruleForm, 'choosedataItemIdList', list);
    },
    closeItem(id) {
      this.ruleForm.dataItemIdList = this.ruleForm.dataItemIdList.filter(e => {
        return e !== id
      })
    },
    clearSelectAll() {
      this.ruleForm.dataItemIdList = []
    },
    selectAll() {
      this.ruleForm.dataItemIdList = this.dataItemListAll.map(item => {
        return item.dataItemId
      })
    },
    queryTableList() {
      let params = {
        page: this.page,
        size: this.size,
        condition: {
          ...this.searchFormData
        }
      }
      device.queryPageList(params).then(res => {
        let { data } = res
        this.total = data.total;
        this.tableData = data.list;
      }).catch(err => {
        console.log(err)
      })
    },
    async clearParam(deviceCode) {
      this.$confirm('此操作将删除该设备所有数据项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let { msg, code } = await dataItem.clearParam({ deviceCode });
        if (code == 1) {
          this.$message.success(msg || '操作成功')
        } else {
          this.$message.error(msg || '操作失败')
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });

    },
    async submitForm() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (this.dataItemFlag == 'lookView') {
            let { msg, code } = await device.updateDataItem({
              deviceCode: this.ruleForm.deviceCode,
              deviceDataItemList: this.ruleForm.choosedataItemIdList
            })
            if (code == 1) {
              this.$message.success(msg)
              this.closeDialog();
            } else {
              this.$message.error(msg)
            }
          } else {
            if (!this.ruleForm.dataItemIdList || !this.ruleForm.dataItemIdList.length) {
              this.$message.warning('请选择数据项')
              return
            };
            let res = await dataItem.addDataItem(this.ruleForm);
            if (res.code == 1) {
              this.$message.success(res.msg)
              this.closeDialog();
            } else {
              this.$message.error(res.msg)
            }
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });

    },
    resetForm(formName = 'ruleForm') {
      this.$refs[formName].resetFields();
    },
    closeDialog() {
      this.dialogVisible = false;
      this.dialogVisible_addItem = false;
      this.ruleForm = {};
      this.formData = {};
      this.queryTableList();
    },
    async handleClickAddItem(row, flag) {
      let { data: list } = await dataItem.queryDataItemByDevice({ deviceCode: row.deviceCode });//已选择的数据项
      let { data: dataItemList } = await deviceType.queryByDeviceTypeId(row.deviceTypeId); //同数据类型的数据项
      if (flag == 'add') {
        this.dataItemList = dataItemList
        let dataItemObj = {}
        list = list.map(item => {
          return dataItemObj[item.funcName + item.paramType] = item
        })
        let chooseList = [];
        this.dataItemList.forEach(item => {
          dataItemObj[item.funcName + item.paramType] && chooseList.push(item.dataItemId)
        })
        console.log(chooseList)
        this.ruleForm = { ...row, dataItemIdList: chooseList };
      } else {
        let choosedataItemIdList = list.map(e => {
          return {
            ...e,
            deviceTypeId: Number(row.deviceTypeId)
          }
        })
        this.ruleForm = { ...row, choosedataItemIdList: choosedataItemIdList }
      }
      this.dataItemFlag = flag
      this.dialogVisible_addItem = true;
    },
    handleClickDel(rowList = []) {
      let list = [];
      rowList.forEach(item => {
        list.push(item.deviceId)
      })
      if (rowList.length == 0) return;
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        device.delList(list).then(res => {
          if (res.code = 1) {
            this.queryTableList();
            this.$message.success('删除成功')
          } else {
            this.$message.warning('删除失败')
          }
        }).catch(err => {
          this.$message.warning('删除失败')
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleClickAddEdit(flag = 'add', row = {}) {
      this.formData = JSON.parse(JSON.stringify(row));
      this.addEditFlag = flag
      this.dialogVisible = true;
    },
    handleSelectionChange(list = []) {
      this.selectionList = list
    },
    handleSizeChange(size) {
      this.size = size;
      this.queryTableList();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.queryTableList();
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => { });
    }
  }
}
</script>

<style lang="scss" scoped>
.row {
  padding-bottom: 15px;
}


.choosedataItemIdList {
  width: 100%;
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;

  .dataItem {
    width: calc(100% / 3 - 20px);
    padding: 10px
  }

  .deviceDataItem {
    padding: 20px 0;
    border-top: 1px dashed #cecece;
    font-weight: bold;
  }
}
</style>
